/**
 * 
 */
package com.credit.service;

import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.credit.entity.NullObject;


/**
 * @author quanzhi
 *
 */
@Service("redisService")
public class RedisService {

	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

	public void setValueDefaultNull(String key, Object value) {
		if (value == null) {
			redisTemplate.opsForValue().set(key, new NullObject());
		} else {
			redisTemplate.opsForValue().set(key, value);
		}
	}
	
	
	public void setValueDefaultNull(String key, Object value, long timeout, TimeUnit unit) {
		if (value == null) {
			redisTemplate.opsForValue().set(key, new NullObject(), timeout, unit);
		} else {
			redisTemplate.opsForValue().set(key, value, timeout, unit);
		}
	}

	public Object getValue(String key) {
		return redisTemplate.opsForValue().get(key);
	}

	public Object getRealValue(String key) {
		Object value = redisTemplate.opsForValue().get(key);
		if (value == null) {
			return null;
		} else if (value instanceof NullObject) {
			return null;
		} else {
			return value;
		}
	}

	
	public void delete(String key) {
		redisTemplate.delete(key);
	}
	
	
	public void saveForZSet(String prefix,String key,Serializable value,double score) {
		
		redisTemplate.opsForZSet().add(prefix+":"+key,value,score);
		
	}

	public void delete(String prefix,String key,Serializable member) {
		
		redisTemplate.opsForZSet().remove(prefix+":"+key, member);
		
	}

	public Set<Object> getForZSet(String prefix,String key,long pageNum,boolean isDesc) {
		Set<Object> object = null;

		long startIndex = (pageNum-1)*20;
		long endIndex = (pageNum-1)*20+20-1;
		if(isDesc){
			object =redisTemplate.opsForZSet().reverseRange(prefix+":"+key, startIndex, endIndex);
		}else{
			object = redisTemplate.opsForZSet().range(prefix+":"+key, startIndex, endIndex);
		}
		
		return object;
	}
	
	public Set<Object> getForZSet(String prefix,String key,boolean isDesc) {
		 Set<Object>  object = null;
			if(isDesc){
				object = redisTemplate.opsForZSet().reverseRange(prefix+":"+key, 0, -1);
			}else{
				object = redisTemplate.opsForZSet().range(prefix+":"+key, 0, -1);
			}
	
		return object;
	}

	public Long getSizeForZSet(String prefix,String key) {
	
		return redisTemplate.opsForZSet().size(prefix+":"+key);
		
	}
	
}
